<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>iframe+postMessage 跨域通信 主页面</title>
    <style>
        iframe{
            width:100%;height:250px;margin:0;padding:0;background: #a2a2a2;
        }
        a{display: none;}
    </style>
</head>
<body>
<h1>主页面</h1>
<iframe id="child" src="http://127.0.0.1:3001/children.html"></iframe>
<div>
    <h2>主页面接收消息区域</h2>
    <span id="message"></span>
    <p>
        <a href="https://blog.csdn.net/tang_yi_/article/details/79401280">
            https://blog.csdn.net/tang_yi_/article/details/79401280
        </a>
    </p>
    <div>
        <input type="text" id="msg"><button type="button" onclick="sendMessage()">父说：</button>
    </div>

</div>
</body>
<script>
    window.onload = function(){
        document.getElementById('child')
            .contentWindow.postMessage("主页面消息", "http://127.0.0.1:3001/children.html");
    }
    window.addEventListener('message', function(event){
        //document.getElementById('message').innerHTML = "收到" + event.origin + "消息：" + event.data;
        this.receiveMessage(event);
        if(event.data === 'getRouter'){
            console.log(event);
        }
    }, false);

    function receiveMessage(event){
        console.log(event);
    }
    function sendMessage() {
        var str=document.getElementById('msg').value;
        console.log(str);
        document.getElementById('child')
            .contentWindow.postMessage(str, "http://127.0.0.1:3001/children.html");
    }
</script>
</html>
